package com.zeta.eduservice.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

@Component
public class Download {
	public  void fileDownLoad(String path,HttpServletResponse response) throws IOException{
			File file = new File(path);		
			  response.setContentType("application/octet-stream;charset=UTF-8");
		        // 设置文件名，fileName是下载文件的文件名
		        response.addHeader("Content-Disposition",
		                "attachment");

		        byte[] buffer = new byte[1024];
				//需要下载文件的字节数组
		        InputStream fis = new FileInputStream(file);
		        buffer = FileCopyUtils.copyToByteArray(fis);
		        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
		        
		        try {
		            OutputStream out = response.getOutputStream();
		            int i = byteArrayInputStream.read(buffer);
		            while (i != -1) {
		                out.write(buffer, 0, i);
		                i = byteArrayInputStream.read(buffer);
		            }
		            out.flush();
			        } catch (IOException e) {
		            e.printStackTrace();
		        }finally {
		            if (byteArrayInputStream != null) {
		                try {
		                    byteArrayInputStream.close();
		                } catch (IOException e) {
		                    e.printStackTrace();
		                }
		            }
		        }
	}

	
}
